package com.powerteam.controller.sys;

import com.powerteam.interceptor.annotation.RequireSession;
import com.powerteam.model.sys.User;
import com.powerteam.service.sys.UserService;
import com.powerteam.vo.ResultData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

/**
 * 登录页相关接口
 *
 * @author jinming.zhang
 * @version 0.0.1
 * @date 2021/12/30
 */
@Controller
public class HomeController {

    @Autowired
    private HttpSession httpSession;

    @Autowired
    private UserService userService;


    /**
     * 登录页
     *
     * @return
     */
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String home() {

        return "sys/home";
    }

    /**
     * 用户登录接口
     *
     * @param user user
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/signIn", method = RequestMethod.POST)
    public ResultData<User> signIn(@RequestBody User user) {

        ResultData<User> result = userService.signIn(user);

        // 如果登录成功，将登录信息放入session中
        if (result.isSuccess()) {
            httpSession.setAttribute("User", result.getData());
        }

        return result;
    }

    /**
     * 用户退出接口
     *
     * @return
     */
    @RequireSession
    @RequestMapping(value = "/signOut", method = RequestMethod.GET)
    public String signOut() {

        // 清除session信息
        httpSession.invalidate();

        // 重定向到根目录
        return "redirect:/";
    }


}
